<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button class="btn1">获取图书</button>
    <button class="btn2">新增图书</button>
    <button class="btn3">修改图书</button>
    <button class="btn4">删除图书</button>
    <script>
        function myAxios(options) {
            const {
                url,
                method = 'get',
                data
            } = options
            return new Promise((resolve, reject) => {
                // 1.实例化异步对象
                const xhr = new XMLHttpRequest()
                // 2.设置请求的 地址 和方法
                xhr.open(method, url)
                xhr.setRequestHeader('content-type', 'application/json')
                // 3.注册回调函数 服务器响应内容回来之后触发
                xhr.addEventListener('load', function () {
                    console.log(xhr.response)
                    // resolve(JSON.parse(xhr.response))
                })
                // 4.发送请求
                xhr.send(JSON.stringify(data))
            })
        }

        document.querySelector('.btn1').addEventListener('click', function () {
            myAxios({
                url: 'http://ajax-api.itheima.net/api/books',
                method: 'get',
            }).then((res) => {
                console.log(res)
            })
        })
        document.querySelector('.btn2').addEventListener('click', function () {
            myAxios({
                url: 'http://ajax-api.itheima.net/api/books',
                method: 'POST',
                data: {
                    bookname: '好好学习',
                    author: '23453',
                    publisher: '2353425',
                },
            }).then((res) => {
                console.log(res)
            })
        })
        document.querySelector('.btn3').addEventListener('click', function () {
            myAxios({
                url: `http://ajax-api.itheima.net/api/books/30`,
                method: 'put',
                data: {
                    bookname: '好好学习9999',
                    author: '23453',
                    publisher: '2353425',
                },
            }).then((res) => {
                console.log(res)
            })
        })
        document.querySelector('.btn4').addEventListener('click', function () {
            myAxios({
                url: `http://ajax-api.itheima.net/api/books/88`,
                method: 'delete',
            }).then((res) => {
                console.log(res)
            })
        })
    </script>
</body>

</html>